<template>
  <a-modal :title="title" :width="900" :visible="visible" :confirmLoading="confirmLoading" @ok="handleOk"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <div class="table-page-search-wrapper">
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol">
              <span slot="label">
                <a-tooltip title="如果填写此值, + 常规路由将会带上此值">
                  <a-icon type="question-circle-o" />
                </a-tooltip>&nbsp;
                路由编码
              </span>
              <a-input v-model="routCode" placeholder="" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row style="margin-bottom: 8px;">
          <a-button @click="handleAdd()" icon="plus" type="primary">新增数据</a-button>
          <a-tooltip placement="topLeft" title="新增增删改查按钮权限">
            <a-button @click="handleCrudAdd()" icon="plus" style="margin-left: 8px" type="primary">常规权限</a-button>
          </a-tooltip>
          <a-tooltip placement="topLeft" title="新增增删改查路由权限">
            <a-button @click="handleRouteAdd()" icon="plus" style="margin-left: 8px" type="primary">常规路由</a-button>
          </a-tooltip>
          <a-tooltip placement="topLeft">
            <a-popconfirm title="确定要删除全部数据吗？" @confirm="handleDelete()">
              <a-button icon="minus" style="margin-left: 8px" type="danger">全部删除</a-button>
            </a-popconfirm>
          </a-tooltip>
        </a-row>
        <a-row>
          <a-form-model ref="form" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules">
            <a-table ref="table" :columns="columns" :rowKey="(record) => record.id" :data-source="form.data"
              :loading="tableLoading" :scroll="{ y: 400 }" :pagination="false">
              <template slot="type" slot-scope="text, record,index">
                <a-form-model-item>
                  <a-select style="width: 120px;background: #fff;color: rgba(0, 0, 0, 0.65);" v-model="record.type"
                    :disabled="record.editable ? false : true">
                    <a-select-option :value="1">
                      按钮
                    </a-select-option>
                    <a-select-option :value="2">
                      路由
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </template>
              <template v-for="(col, index) in ['name', 'code']" :slot="col" slot-scope="text, record,index">
                <a-form-model-item :prop="`data.${index}.${col}`" :key="index" :rules="rules[col]">
                  <template>
                    <a-input style="margin: -5px 0" v-model="record[col]" />
                  </template>
                </a-form-model-item>
              </template>
              <template slot="operation" slot-scope="text, record, index">
                <a-form-model-item>
                  <div class="editable-row-operations">
                    <span style="display: flex;">
                      <a-popconfirm title="确定删除吗?" @confirm="() => remove(record.id)">
                        <a style="margin-right: 10px;">删除</a>
                      </a-popconfirm>
                    </span>
                  </div>
                </a-form-model-item>
              </template>
            </a-table>
          </a-form-model>
        </a-row>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { STable } from '@/components'
export default {
  components: {
    STable
  },
  data() {
    return {
      gutter: 24,
      mdSize: 24,
      smSize: 24,
      title: '编辑数据',
      labelCol: {
        md: { span: 6 },
        sm: { span: 4 }
      },
      wrapperCol: {
        md: { span: 16 },
        sm: { span: 20 }
      },
      visible: false,
      queryParam: {},
      form: { data: [] },
      confirmLoading: false,
      routCode: '',
      info: {},
      columns: columns,
      tableLoading: false,
      rules: {
        name: [{ required: true, message: '请输入名称！' }],
        code: [{ required: true, message: '请输入编码！' }]
      }
    }
  },
  methods: {
    handSearch() {
      this.tableLoading = true
      this.queryParam.menuId = this.info.id
      this.$http.get('/sysPermissions', { params: this.queryParam }).then(res => {
        if (res.code === 200) {
          this.form.data = res.result
          this.data = res.result
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    remove(key) {
      const target = this.form.data.find(item => key === item.id)
      if (target) {
        this.form.data = this.form.data.filter(item => item.id !== key)
      }
    },
    handleAdd() {
      const count = this.form.data.length + 1
      const newData = {
        id: count,
        name: '',
        code: '',
        menuId: this.info.id,
        type: 1,
        isNew: true
      }
      this.form.data = [...this.form.data, newData]
      this.edit(count, true)
    },
    generateUniqueId() {
      const timestamp = new Date().getTime()
      const randomNum = Math.floor(Math.random() * 1000000)
      return timestamp + randomNum
    },
    handleCrudAdd() {
      const newData = [
        {
          id: this.generateUniqueId(),
          name: this.info.name + '-增加按钮',
          code: 'add',
          menuId: this.info.id,
          type: 1,
          isNew: false
        },
        {
          id: this.generateUniqueId(),
          name: this.info.name + '-修改按钮',
          code: 'update',
          menuId: this.info.id,
          type: 1,
          isNew: false
        },
        {
          id: this.generateUniqueId(),
          name: this.info.name + '-删除按钮',
          code: 'delete',
          menuId: this.info.id,
          type: 1,
          isNew: false
        },
        {
          id: this.generateUniqueId(),
          name: this.info.name + '-查询按钮',
          code: 'get',
          menuId: this.info.id,
          type: 1,
          isNew: false
        }
      ]
      this.form.data = [...this.form.data, ...newData]
    },
    handleRouteAdd() {
      let path = ''
      if (this.routCode) {
        path = this.routCode + '/'
      }
      const newData = [
        {
          id: this.generateUniqueId(),
          name: this.info.name + '-增加路由',
          code: path + 'add',
          menuId: this.info.id,
          type: 2,
          isNew: false
        },
        {
          id: this.generateUniqueId(),
          name: this.info.name + '-修改路由',
          code: path + 'update',
          menuId: this.info.id,
          type: 2,
          isNew: false
        },
        {
          id: this.generateUniqueId(),
          name: this.info.name + '-删除路由',
          code: path + 'delete',
          menuId: this.info.id,
          type: 2,
          isNew: false
        },
        {
          id: this.generateUniqueId(),
          name: this.info.name + '-查询路由',
          code: path + 'get',
          menuId: this.info.id,
          type: 2,
          isNew: false
        },
        {
          id: this.generateUniqueId(),
          name: this.info.name + '-分页路由',
          code: path + 'page',
          menuId: this.info.id,
          type: 2,
          isNew: false
        }
      ]
      this.form.data = [...this.form.data, ...newData]
    },
    handleDelete() {
      this.form.data = []
    },
    // 初始化方法
    detail(record) {
      this.info = record
      this.handSearch()
      this.visible = true
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        if (!this.form.data.length) {
          this.$message.error('请添加菜单权限')
          return
        }
        this.confirmLoading = true
        this.$http.post('/sysPermissions', this.form.data).then(res => {
          if (res.code === 200) {
            this.$message.success('保存成功')
            this.visible = false
            this.$emit('ok')
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      })
    },
    handleCancel() {
      this.close()
    }
  }
}

const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    width: '25%',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '编码',
    dataIndex: 'code',
    width: '25%',
    scopedSlots: { customRender: 'code' }
  },
  {
    title: '类型',
    dataIndex: 'type',
    width: '25%',
    scopedSlots: { customRender: 'type' }
  },
  {
    title: '操作',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]
</script>
